/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Administrador
 */
public abstract class GenericoDao <T,PK extends Serializable > {
 public abstract T save (T t);
 public abstract List<T> getAll();

 public T persist (T bo){
     List <T> allObjects = null;

     //valido que el archivo exista
     File file = new File("C:/user");
     if (file.exists()){
         //obtiene los datos que existen el archivo
         allObjects = getAll(bo.getClass() );

     }else{
         allObjects = new ArrayList<T>();
     }

     // Agregar el objeto a serializar
     allObjects.add(bo);
     FileOutputStream fos = null;
     ObjectOutputStream out = null;
     try{
         fos = new FileOutputStream(file);
         out = new ObjectOutputStream(fos);
         out.writeObject(allObjects);
         out.close();
     } catch (IOException ex) {
         ex.printStackTrace();
     }

     return (bo);

 }

 public List <T> getAll(Class clazz) {
             FileInputStream fis = null;
            ObjectInputStream in = null;
            List listResult = new ArrayList();
        try {

            fis = new FileInputStream("C:/user");
            in = new ObjectInputStream(fis);
            listResult = (ArrayList) in.readObject();
            in.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(GenericoDao.class.getName()).log(Level.SEVERE, null, ex);
        }catch (ClassNotFoundException ex) {
            Logger.getLogger(GenericoDao.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GenericoDao.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
           return listResult;
 }

}
